package com.ssm.controller.admin;


import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.codec.Base64;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ssm.model.mapper.ActionLogMapper;
import com.ssm.model.mapper.ActionMapper;
import com.ssm.model.mapper.UserGroupMapper;
import com.ssm.model.mapper.UserInfoMapper;
import com.ssm.model.mapper.UserMapper;
import com.ssm.model.mapper.UserRuleMapper;
import com.ssm.model.mapper.UsercodeMapper;
import com.ssm.model.mapper.WebSettingMapper;
import com.ssm.util.SSMUtil;

import tk.mybatis.mapper.entity.Example;

import com.ssm.controller.SSMController;
import com.ssm.model.bean.SsmActionLog;
import com.ssm.model.bean.SsmActions;
import com.ssm.model.bean.SsmUserGroup;
import com.ssm.model.bean.SsmUserInformation;
import com.ssm.model.bean.SsmUserRules;
import com.ssm.model.bean.SsmUsercode;
import com.ssm.model.bean.SsmUsers;
import com.ssm.model.bean.SsmWebSetting;


/**
 * SSM Controller用户类
 * 
 * @author WTC<546895488@qq.com>
 * @version 2016/1/29
 * */
@SuppressWarnings("rawtypes")
@Controller
@RequestMapping(value="User")
public class UserController extends AdminBaseController {
	/**
	 * 登陆页面界面及登陆校验
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value="login")
	public String Login(HttpServletRequest request,SsmUsers loginuser,RedirectAttributes redirectAttributes,
			String code,HttpSession httpSession,HttpServletResponse response)
	{
		Cookie cookie=this.getCookieByName(request, "usercode");

		if(loginuser.getPassword()==null&&cookie==null)
		{
			
			System.out.println("没登陆过···");
			return "User/login";
		}
		else
		{
			//登录用cookie或密码
			System.out.println(cookie==null);
			if(cookie==null)
			{
				if(!(code.equalsIgnoreCase(httpSession.getAttribute("code").toString()))) {  //忽略验证码大小写
					System.out.println("验证码错误");
		            return "User/login";
		        }
				else
				{
					try {
						SecurityUtils.getSubject().login(new UsernamePasswordToken(loginuser.getUsername(), loginuser.getPassword()));
						UserMapper um=M.getMapper(UserMapper.class);
						loginuser=um.selectOne(loginuser);
						httpSession.setMaxInactiveInterval(-1);
						httpSession.setAttribute(this.CURRENT_LOGIN_USER, loginuser);
						
						if(request.getParameter("remember")!=null)
						{
							String str = Long.toString(this.nowTime());  
							String base64Encoded = Base64.encodeToString(str.getBytes());  
							this.addCookie(response, "usercode", base64Encoded);
							
							System.out.println(base64Encoded);
							
							String codevalue=base64Encoded;
							UsercodeMapper ucm=M.getMapper(UsercodeMapper.class);
							SsmUsercode usercode=new SsmUsercode();
							usercode.setUsercode(codevalue);
							System.out.println("userid:"+loginuser.getId());
							usercode.setUserid(loginuser.getId());
							ucm.insert(usercode);
							
							//String str2 = Base64.decodeToString(base64Encoded);  
						}
						
						this.analysisAction("login_ok",request);
						return "redirect:/home/index";
						} 
					catch (AuthenticationException e) {
						redirectAttributes.addFlashAttribute("message","用户名或密码错误");
						System.out.println("用户名或密码错误");
						return "User/login";
						}
					catch (Exception e) {
						
						redirectAttributes.addFlashAttribute("message",e.getMessage());
						System.out.println(e.getMessage());
						return "User/login";
						}
				}
				
			}
			else
			{
				String codevalue=cookie.getValue();
				UsercodeMapper ucm=M.getMapper(UsercodeMapper.class);
				SsmUsercode usercode=new SsmUsercode();
				usercode.setUsercode(codevalue);
				usercode=ucm.selectOne(usercode);
				if(usercode==null)//cookie 无效
				{
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					System.out.println("cookie 无效");
					return "User/login";
				}
				System.out.println("cookie有效，用cookies登录");
				UserMapper um=M.getMapper(UserMapper.class);
				loginuser=um.selectByPrimaryKey(usercode.getUserid());
				try {
				SecurityUtils.getSubject().login(new UsernamePasswordToken(loginuser.getUsername(), loginuser.getPassword()));
				httpSession=request.getSession();
				httpSession.setAttribute(this.CURRENT_LOGIN_USER,loginuser);
				return "redirect:/home/index";
				} 
				catch (AuthenticationException e) {
				redirectAttributes.addFlashAttribute("message","用户名或密码错误");
				System.out.println("用户名或密码错误");
				return "User/login";
				}
				catch (Exception e) {
					redirectAttributes.addFlashAttribute("message",e.getMessage());
					System.out.println("adsfa");
					return "User/login";
					}
			}
		}
			
	}

	
	/**
	 * 无效界面
	 * @return
	 */
	@RequestMapping(value="666")
	public String NoDoing()
	{
		return "User/666";
	}
	
	/*
	 * 
	 */
	@RequestMapping(value="info")
	public String userInfo(HttpServletRequest request)
	{
		Example example=new Example(SsmActionLog.class);
		example.createCriteria().andCondition("userid="+this.getUserID(request));
		this.List2Table(ActionLogMapper.class,example,request,false);	
		
		
		SsmUsers user=new SsmUsers();
		UserMapper um=M.getMapper(UserMapper.class);
		user=um.selectByPrimaryKey(this.getUserID(request));
		
		SsmUserInformation userinfo=new SsmUserInformation();
		UserInfoMapper uim=M.getMapper(UserInfoMapper.class);
		userinfo.setUserid(this.getUserID(request));
		userinfo=uim.selectOne(userinfo);
		
		request.setAttribute("userinfo", userinfo);
		request.setAttribute("user",user);
		return "User/info";
	}
	
	
	
	/**
	 * 登陆页面界面及登陆校验
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="register")
	public String Resigter(HttpServletRequest request,Model model,SsmUsers user,SsmUserInformation userinfo)
	{
		if(request.getMethod()=="POST")//注册校验
		{
			
				user.setCreatetime(this.nowTime().toString());
			    UserMapper um=M.getMapper(UserMapper.class);
			    UserInfoMapper uim=M.getMapper(UserInfoMapper.class);
			    UserGroupMapper ugm=M.getMapper(UserGroupMapper.class);
			    //设置用户默认状态
			   
			    user.setStatus(S.getInteger("userstatus"));
			    //添加用户
			    um.insert(user);
			    user=um.selectOne(user);
			    
			   //添加用户信息
			    userinfo.setUserid(user.getId());
			    uim.insert(userinfo);
			    
			    //默认用户组
			    SsmUserGroup usergroup=new SsmUserGroup();
			    usergroup.setCreatetime(this.nowTime().toString());
			    usergroup.setUserid(user.getId());
			    //设置默认分配用户组
			    usergroup.setGroupid(S.getInteger("usergroup"));
			    //设置默认分配用户组是否用
			    usergroup.setStatus(S.getInteger("enusergroup"));
			    ugm.insert(usergroup);
			    
			    //输出用户信息
			    model.addAttribute(user);
				return "User/register_ok";
		}
		else{//注册界面
			return "User/register";
		}
	}

	/**
	 * 用户状态管理
	 * @param request
	 * @return
	 */
	@RequestMapping(value="user_status")
	public String UserStatus(HttpServletRequest request)
	{
			UserMapper um=M.getMapper(UserMapper.class);
			List<SsmUsers> list=um.selectAll();
			this.List2Table(UserMapper.class,null,request,false);	
			request.setAttribute("list", list);
			request.setAttribute("WEB_TITLE", "用户状态界面");
			return "User/user_status";
	}
	
	/**
	 * 编辑用户状态
	 * @param request
	 * @return
	 */
	@RequestMapping(value="status_edit")
	public String UserStatusEdit(HttpServletRequest request,SsmUsers user)
	{
		UserMapper um=M.getMapper(UserMapper.class);
		
		if(request.getMethod()=="POST")//更新
		{
			
			um.updateByPrimaryKeySelective(user);
			request.setAttribute("WEB_TITLE", "修改用户状态成功！");
			return "User/user_status";
			
		}
		else//编辑
		{
			Integer id=Integer.parseInt(request.getParameter("userid"));
			user=um.selectByPrimaryKey(id);
			request.setAttribute("user",user);
			request.setAttribute("WEB_TITLE", "修改用户状态");
			return "User/status_edit";
		}
		
	}
	
	@RequestMapping(value="info_edit")
	public String UserInfoEdit(HttpServletRequest request,SsmUserInformation userinfo)
	{
		UserInfoMapper uim=M.getMapper(UserInfoMapper.class);
		if(request.getMethod()=="POST"){//更新用户信息
			uim.updateByPrimaryKeySelective(userinfo);
			request.setAttribute("WEB_TITLE", "修改用户信息成功！");
			//return "user_info";
			return "User/login_ok";
		}
		else//编辑用户信息
		{
			Integer id=Integer.parseInt(request.getParameter("userid"));
			userinfo.setUserid(id);
			userinfo=uim.selectOne(userinfo);
			request.setAttribute("userinfo",userinfo);
			request.setAttribute("WEB_TITLE", "查看用户信息");
			return "User/info_edit";
		}
	}
	
	
	/**
	 * @param method
	 * @param id
	 * @return
	 */
	@RequestMapping(value="changeStatus")
	public String changeStatus(HttpServletRequest request)
	{
		changeStatus(ActionMapper.class,request);
		return "redirect:index";
	}
	
	@RequestMapping(value="logout")    
    public String logout(RedirectAttributes redirectAttributes ){   
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息  
        SecurityUtils.getSubject().logout();    
        redirectAttributes.addFlashAttribute("message", "您已安全退出");    
        return "User/login";  
    }   
	
}
